<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\StoreOrder;
use App\StoreProduct;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Excels\Exports\OrderExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Excels\Imports\OrderImports;

class OrderController extends Controller
{
    /**
     * @auther yang
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        $wd   = $request->input('wd');
        $start_time   = $request->input('start_time');
        $end_time   = $request->input('end_time');
        $order_status   = $request->input('order_status', -1);
        $merchant_id = $request->session()->get('admin.id');
        $where = [
            ['order', 'id', 'desc'],
            ['merchant_id', 'eq', $merchant_id]
        ];

        $db = DB::table('eb_store_order');

        // 搜索
        if (!empty($wd)) {
            $db->orWhere('real_name','like', $wd);
            $db->orWhere('user_phone','like', $wd);
            $db->orWhere('order_id','like', $wd);
        }

        // 创建时间
        if (!empty($start_time)) {
            $where[] = ['add_time','gt', strtotime($start_time)];
        }
        if (!empty($end_time)) {
            $where[] = ['add_time','lt', strtotime($end_time)];
        }

        // 订单状态
        switch ($order_status)
        {
            case 1: # 未支付
                $where[] = ['paid','eq', 0];
                $where[] = ['status','eq', 0];
                break;
            case 2: # 未发货
                $where[] = ['paid','eq', 1];
                $where[] = ['status','eq', 0];
                $where[] = ['shipping_type','eq', 1];
                $where[] = ['refund_status','eq', 0];
                break;
            case 3: # 未核销
                $where[] = ['paid','eq', 1];
                $where[] = ['status','eq', 0];
                $where[] = ['shipping_type','eq', 2];
                $where[] = ['refund_status','eq', 0];
                break;
            case 4: # 待收货
                $where[] = ['paid','eq', 1];
                $where[] = ['status','eq', 1];
                $where[] = ['shipping_type','eq', 1];
                $where[] = ['refund_status','eq', 0];
                break;
            case 5: # 未核销
                $where[] = ['paid','eq', 1];
                $where[] = ['status','eq', 1];
                $where[] = ['shipping_type','eq', 2];
                $where[] = ['refund_status','eq', 0];
                break;
            case 6: # 待评价
                $where[] = ['paid','eq', 1];
                $where[] = ['status','eq', 2];
                $where[] = ['refund_status','eq', 0];
                break;
            case 7: # 已完成
                $where[] = ['paid','eq', 1];
                $where[] = ['status','eq', 3];
                $where[] = ['refund_status','eq', 0];
                break;
            case 8: # 退款中
                $where[] = ['paid','eq', 1];
                $where[] = ['refund_status','eq', 1];
                break;
            case 9: # 已退款
                $where[] = ['paid','eq', 1];
                $where[] = ['refund_status','eq', 2];
                break;
        }

        $db = format_sql($db, $where);
        $data = $db->paginate(10);

        $list = [];
        foreach ($data as $item) {
            $item = (array)$item;
            $user = DB::table('eb_user')->where('uid', $item['uid'])->first();
            $cart_infos = Db::table('eb_store_order_cart_info')->where('oid', $item['id'])->pluck('cart_info');
            $info = [];
            if (!empty($cart_infos)) {
                foreach ($cart_infos as $v) {
                    $cart_info = json_decode($v, true);
                    if (!isset($cart_info['productInfo'])) $cart_info['productInfo'] = [];
                    $info[]['cart_info'] = $cart_info;
                }
            }

            $item['info'] = $info;
            $item['spread_nickname'] = Db::table('eb_user')->where('uid', $user->spread_uid)->value('nickname');
            //$item['nickname'] = $user->nickname;
            $item['back_integral'] = $item['back_integral'] ?: 0;
            if ($item['paid'] == 1) {
                switch ($item['pay_type']) {
                    case 'weixin':
                        $item['pay_type_name'] = '微信支付';
                        break;
                    case 'yue':
                        $item['pay_type_name'] = '余额支付';
                        break;
                    case 'offline':
                        $item['pay_type_name'] = '线下支付';
                        break;
                    default:
                        $item['pay_type_name'] = '其他支付';
                        break;
                }
            } else {
                switch ($item['pay_type']) {
                    default:
                        $item['pay_type_name'] = '未支付';
                        break;
                    case 'offline':
                        $item['pay_type_name'] = '线下支付';
                        $item['pay_type_info'] = 1;
                        break;
                }
            }
            if ($item['paid'] == 0 && $item['status'] == 0) {
                $item['status_name'] = '未支付';
                $item['operate_status'] = 1;
            } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['shipping_type'] == 1 && $item['refund_status'] == 0) {
                $item['status_name'] = '未发货';
                $item['operate_status'] = 2;
            } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['shipping_type'] == 2 && $item['refund_status'] == 0) {
                $item['status_name'] = '未核销';
                $item['operate_status'] = 3;
            } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['shipping_type'] == 1 && $item['refund_status'] == 0) {
                $item['status_name'] = '待收货';
                $item['operate_status'] = 4;
            } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['shipping_type'] == 2 && $item['refund_status'] == 0) {
                $item['status_name'] = '未核销';
                $item['operate_status'] = 5;
            } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
                $item['status_name'] = '待评价';
                $item['operate_status'] = 6;
            } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
                $item['status_name'] = '已完成';
                $item['operate_status'] = 7;
            } else if ($item['paid'] == 1 && $item['refund_status'] == 1) {
                $item['status_name'] = '退款审核中';
                $item['operate_status'] = 8;
            } else if ($item['paid'] == 1 && $item['refund_status'] == 2) {
                $item['status_name'] = '已退款';
                $item['operate_status'] = 9;
            }
            if ($item['paid'] == 0 && $item['status'] == 0 && $item['refund_status'] == 0) {
                $item['_status'] = 1;
            } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
                $item['_status'] = 2;
            } else if ($item['paid'] == 1 && $item['refund_status'] == 1) {
                $item['_status'] = 3;
            } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
                $item['_status'] = 4;
            } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
                $item['_status'] = 5;
            } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
                $item['_status'] = 6;
            } else if ($item['paid'] == 1 && $item['refund_status'] == 2) {
                $item['_status'] = 7;
            }
            $list[] = (object)$item;
        }

        //dd($list);
        return view('admin.order_list', ['list' => $list, 'appends_wd' => $data, 'wd' => $wd]);
    }

    /**
     * 商品详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        $id = $request->input('id', 0);
        $data = StoreOrder::detail([['id', 'eq', $id]]);
        $user = DB::table('eb_user')->where('uid', $data['uid'])->first();
        $data['spread_nickname'] = Db::table('eb_user')->where('uid', $user->spread_uid)->value('nickname');
        if ($data['paid'] == 0 && $data['status'] == 0) {
            $data['status_name'] = '未支付';
            $data['operate_status'] = 1;
        } else if ($data['paid'] == 1 && $data['status'] == 0 && $data['shipping_type'] == 1 && $data['refund_status'] == 0) {
            $data['status_name'] = '未发货';
            $data['operate_status'] = 2;
        } else if ($data['paid'] == 1 && $data['status'] == 0 && $data['shipping_type'] == 2 && $data['refund_status'] == 0) {
            $data['status_name'] = '未核销';
            $data['operate_status'] = 3;
        } else if ($data['paid'] == 1 && $data['status'] == 1 && $data['shipping_type'] == 1 && $data['refund_status'] == 0) {
            $data['status_name'] = '待收货';
            $data['operate_status'] = 4;
        } else if ($data['paid'] == 1 && $data['status'] == 1 && $data['shipping_type'] == 2 && $data['refund_status'] == 0) {
            $data['status_name'] = '未核销';
            $data['operate_status'] = 5;
        } else if ($data['paid'] == 1 && $data['status'] == 2 && $data['refund_status'] == 0) {
            $data['status_name'] = '待评价';
            $data['operate_status'] = 6;
        } else if ($data['paid'] == 1 && $data['status'] == 3 && $data['refund_status'] == 0) {
            $data['status_name'] = '已完成';
            $data['operate_status'] = 7;
        } else if ($data['paid'] == 1 && $data['refund_status'] == 1) {
            $refundReasonTime = date('Y-m-d H:i', $data['refund_reason_time']);
            $refundReasonWapImg = json_decode($data['refund_reason_wap_img'], true);
            $refundReasonWapImg = $refundReasonWapImg ? $refundReasonWapImg : [];
            $img = '';
            if (count($refundReasonWapImg)) {
                foreach ($refundReasonWapImg as $itemImg) {
                    if (strlen(trim($itemImg)))
                        $img .= '<img style="height:50px;" src="' . $itemImg . '" />';
                }
            }
            if (!strlen(trim($img))) $img = '无';
            $data['operate_status'] = 8;
        } else if ($data['paid'] == 1 && $data['refund_status'] == 2) {
            $data['status_name'] = '已退款';
            $data['operate_status'] = 9;
        }

        return view('admin.order_detail', ['data' => (object)$data]);
    }

    public function markView(Request $request)
    {
        $params = getParams($request->input(), ['id'], 0, 1);
        $data = StoreOrder::detail([['id', 'eq', $params['id']]]);
        return view('admin.order_mark', ['data' => $data]);
    }

    public function mark(Request $request)
    {
        $params = getParams($request->input(), ['id', 'content'], 0, 1);
        $result = StoreOrder::edit([['id', 'eq', $params['id']]], ['remark' => $params['content']]);
        if ($result === false) {
            reply_error('添加备注失败');
        }
        reply([], '添加备注成功');
    }

    public function orderLog(Request $request)
    {
        $id = $request->input('id', 0);
        $list = Db::table('eb_store_order_status')->where('oid', $id)->orderBy('change_time', 'desc')->get();
        return view('admin.order_log', ['list' => $list]);
    }

    public function deliveryView(Request $request)
    {
        $id = $request->input('id', 0);
        $list =  Db::table('eb_express')->where('is_show',1)->orderBy('sort', 'desc')->pluck('name','id');
        return view('admin.order_delivery', ['list' => $list, 'id' => $id]);
    }

    /**
     * 发货
     * @auther yang
     * @param Request $request
     * @return array
     */
    public function delivery(Request $request)
    {
        $params = getParams($request->input(), ['type'], 0, 1);
        switch ((int)$params['type']){
            case 1:
                //发货
                $data = getParams($request->input(), ['id', 'type', 'delivery_id'], 0, 1);
                $data['delivery_name'] = Db::table('eb_express')->where('id', $data['delivery_id'])->value('name');
                $result = crmeb_curl(1, $data);
                break;
            case 2:
                //送货
                $data = getParams($request->input(), ['id', 'type', 'sh_delivery_name','sh_delivery_id'], 0, 1);
                $result = crmeb_curl(1, $data);
                break;
            case 3:
                //虚拟发货
                $data = getParams($request->input(), ['id', 'type'], 0, 1);
                $result = crmeb_curl(1, $data);
                break;
            default:
                $result = ['code' => 0, 'msg' => '暂时不支持其他发货类型', 'data' => []];
                break;
        }
        return $result;
    }

    /**
     * 确认收货
     * @auther yang
     * @param Request $request
     * @return array
     */
    public function take_delivery(Request $request)
    {
        $params = getParams($request->input(), ['id'], 0, 1);
        $result = crmeb_curl(4, [], '/id/'.$params['id'], 'get');
        return $result;
    }

    /**
     * 退款
     * @auther yang
     * @param Request $request
     * @return array
     */
    public function refund(Request $request){
        $params = getParams($request->input(), ['id', 'type', 'refund_price'], 0, 1);
        $result = crmeb_curl(2, $params);
        return $result;
    }

    public function refundView(Request $request){
        $id = $request->input('id', 0);
        $order = StoreOrder::detail([['id', 'eq', $id]]);
        return view('admin.order_refund', ['order' => (object)$order]);
    }

    /**
     * 修改
     * @auther yang
     * @param Request $request
     * @return array
     */
    public function editView(Request $request)
    {
        $id = $request->input('id');
        $order = StoreOrder::detail([['id', 'eq', $id]]);
        return view('admin.order_edit', ['order' => (object)$order]);
    }

    /**
     * 修改
     * @auther yang
     * @param Request $request
     * @return array
     */
    public function edit(Request $request)
    {
        $params = $request->input();
        $params = getParams($params, [
            'id',
            'order_id',
            'total_price',
            'total_postage',
            'pay_price',
            'pay_postage',
            'gain_integral',
        ], 0, 1);
        $result = crmeb_curl(3, $params, '?id='.$params['id']);
        return $result;
    }

    /**
     * 删除
     * @auther yang
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request)
    {
        $id = $request->input('id');

        if (empty($id)) {
            reply_error('参数缺失');
        } else {
            $product = StoreProduct::detail([['id','eq',$id]]);
        }

        if (!empty($product)) {
            StoreProduct::edit([['id','eq',$id]], ['is_del' => 1]);
        }

        reply([],'删除成功');
    }

    /**
     * 删除
     * @auther yang
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function export(Request $request)
    {
        $wd   = $request->input('wd');
        $start_time   = $request->input('start_time');
        $end_time   = $request->input('end_time');
        $order_status   = $request->input('order_status', -1);
        $merchant_id = $request->session()->get('admin.id');
        $where = [
            ['order', 'id', 'desc'],
            ['merchant_id', 'eq', $merchant_id]
        ];

        $db = DB::table('eb_store_order');

        // 搜索
        if (!empty($wd)) {
            $db->orWhere('real_name','like', $wd);
            $db->orWhere('user_phone','like', $wd);
            $db->orWhere('order_id','like', $wd);
        }

        // 创建时间
        if (!empty($start_time)) {
            $where[] = ['add_time','gt', strtotime($start_time)];
        }
        if (!empty($end_time)) {
            $where[] = ['add_time','lt', strtotime($end_time)];
        }

        // 订单状态
        switch ($order_status)
        {
            case 1: # 未支付
                $where[] = ['paid','eq', 0];
                $where[] = ['status','eq', 0];
                break;
            case 2: # 未发货
                $where[] = ['paid','eq', 1];
                $where[] = ['status','eq', 0];
                $where[] = ['shipping_type','eq', 1];
                $where[] = ['refund_status','eq', 0];
                break;
            case 3: # 未核销
                $where[] = ['paid','eq', 1];
                $where[] = ['status','eq', 0];
                $where[] = ['shipping_type','eq', 2];
                $where[] = ['refund_status','eq', 0];
                break;
            case 4: # 待收货
                $where[] = ['paid','eq', 1];
                $where[] = ['status','eq', 1];
                $where[] = ['shipping_type','eq', 1];
                $where[] = ['refund_status','eq', 0];
                break;
            case 5: # 未核销
                $where[] = ['paid','eq', 1];
                $where[] = ['status','eq', 1];
                $where[] = ['shipping_type','eq', 2];
                $where[] = ['refund_status','eq', 0];
                break;
            case 6: # 待评价
                $where[] = ['paid','eq', 1];
                $where[] = ['status','eq', 2];
                $where[] = ['refund_status','eq', 0];
                break;
            case 7: # 已完成
                $where[] = ['paid','eq', 1];
                $where[] = ['status','eq', 3];
                $where[] = ['refund_status','eq', 0];
                break;
            case 8: # 退款中
                $where[] = ['paid','eq', 1];
                $where[] = ['refund_status','eq', 1];
                break;
            case 9: # 已退款
                $where[] = ['paid','eq', 1];
                $where[] = ['refund_status','eq', 2];
                break;
        }

        $db = format_sql($db, $where);
        $data = $db->get();

        $list = [];
        foreach ($data as $item) {
            $item = (array)$item;
            $user = DB::table('eb_user')->where('uid', $item['uid'])->first();
            $cart_infos = Db::table('eb_store_order_cart_info')->where('oid', $item['id'])->pluck('cart_info');
            $info = [];
            if (!empty($cart_infos)) {
                foreach ($cart_infos as $v) {
                    $cart_info = json_decode($v, true);
                    if (!isset($cart_info['productInfo'])) $cart_info['productInfo'] = [];
                    $info[]['cart_info'] = $cart_info;
                }
            }

            $item['info'] = $info;
            $item['spread_nickname'] = Db::table('eb_user')->where('uid', $user->spread_uid)->value('nickname');
            //$item['nickname'] = $user->nickname;
            $item['back_integral'] = $item['back_integral'] ?: 0;
            if ($item['paid'] == 1) {
                switch ($item['pay_type']) {
                    case 'weixin':
                        $item['pay_type_name'] = '微信支付';
                        break;
                    case 'yue':
                        $item['pay_type_name'] = '余额支付';
                        break;
                    case 'offline':
                        $item['pay_type_name'] = '线下支付';
                        break;
                    default:
                        $item['pay_type_name'] = '其他支付';
                        break;
                }
            } else {
                switch ($item['pay_type']) {
                    default:
                        $item['pay_type_name'] = '未支付';
                        break;
                    case 'offline':
                        $item['pay_type_name'] = '线下支付';
                        $item['pay_type_info'] = 1;
                        break;
                }
            }
            if ($item['paid'] == 0 && $item['status'] == 0) {
                $item['status_name'] = '未支付';
                $item['operate_status'] = 1;
            } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['shipping_type'] == 1 && $item['refund_status'] == 0) {
                $item['status_name'] = '未发货';
                $item['operate_status'] = 2;
            } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['shipping_type'] == 2 && $item['refund_status'] == 0) {
                $item['status_name'] = '未核销';
                $item['operate_status'] = 3;
            } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['shipping_type'] == 1 && $item['refund_status'] == 0) {
                $item['status_name'] = '待收货';
                $item['operate_status'] = 4;
            } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['shipping_type'] == 2 && $item['refund_status'] == 0) {
                $item['status_name'] = '未核销';
                $item['operate_status'] = 5;
            } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
                $item['status_name'] = '待评价';
                $item['operate_status'] = 6;
            } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
                $item['status_name'] = '已完成';
                $item['operate_status'] = 7;
            } else if ($item['paid'] == 1 && $item['refund_status'] == 1) {
                $item['status_name'] = '退款审核中';
                $item['operate_status'] = 8;
            } else if ($item['paid'] == 1 && $item['refund_status'] == 2) {
                $item['status_name'] = '已退款';
                $item['operate_status'] = 9;
            }
            $list[] = (object)$item;
        }

        //dd($list);

        $excel_data = [];

        foreach ($list as $item) {

            $product_names = [];
            foreach ($item->info as $pro) {
                $product_names[] = $pro['cart_info']['productInfo']['store_name'];
            }
            $product_names = implode(' - ', $product_names);

            $excel_data[] = [
                $item->order_id,        //'订单号'
                $item->user_phone,        //'电话'
                $item->real_name,        //'收货人姓名'
                $item->user_address,         //'收货地址'
                $product_names,        //'商品信息'
                $item->total_price,        //'总价格'
                $item->pay_price,        //'实际支付'
                $item->total_postage,        //'邮费'
                $item->deduction_price,        //'优惠金额'
                $item->pay_type_name,        //'支付状态'
                date('Y-m-d H:i:s', $item->pay_time),        //'支付时间'
                $item->status_name,        //'订单状态'
                date('Y-m-d H:i:s', $item->add_time),        //'下单时间'
                $item->mark,        //'用户备注'
            ];
        }

        $headings = [
            '订单号',
            '电话',
            '收货人姓名',
            '收货地址',
            '商品信息',
            '总价格',
            '实际支付',
            '邮费',
            '优惠金额',
            '支付状态',
            '支付时间',
            '订单状态',
            '下单时间',
            '用户备注'
        ];

        return Excel::download(new OrderExport($excel_data, $headings), '订单-'.date('Y-m-d H:i').'.xlsx',null, $headings);
    }


    public function importView()
    {
        return view('admin.order_import');
    }
    /**
     * 导入发货数据
     * @auther yang
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function import(Request $request)
    {
        $file = $request->file('excel');
        if (empty($file)) reply_error('请上传文件');

        $data = Excel::toArray(new OrderImports(), $file);
        if (empty($data)) reply_error('文件无内容');
        $data = $data[0];
        unset($data[0]);
        //return $data;

        foreach ($data as $key => $item) {
            $item = [
                'order_id' => $item[0],
                'delivery_type' => $item[1],
                'delivery_name' => $item[2],
                'delivery_id' => $item[3],
            ];

            getParams($item, ['order_id', 'delivery_type'], 0, 1);

            $order = StoreOrder::detail([['order_id' , 'eq', $item['order_id']]], ['id']);
            if (empty($order['id'])) reply_error('订单号不正确');

            switch ($item['delivery_type'])
            {
                case '快递发货':
                    //发货
                    getParams($item, ['delivery_name', 'delivery_id'], 0, 1);
                    $delivery_name = Db::table('eb_express')->where('name', $item['delivery_name'])->value('name');
                    if (empty($delivery_name)) reply_error('快递名称错误');
                    $item['delivery_type'] = 1;
                    break;
                case '线下送货':
                    //送货
                    getParams($item, ['delivery_name', 'delivery_id'], 0, 1);
                    $item['delivery_type'] = 2;
                    break;
                case '虚拟发货':
                    //送货
                    $item['delivery_type'] = 3;
                    break;
            }
            $item['id'] = $order['id'];
            $data[$key] = $item;
        }

        foreach ($data as $item) {
            $result = crmeb_curl(1, $item);
            if ($result['code'] != 200) reply_error('发货失败');
        }

        reply([], '发货成功');
    }

    public function importTem()
    {
        return response()->download(base_path('resources/excel/import_template.xlsx'));
    }
}
